package com.xz.danhuaapi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xz.danhuaapi.common.ErrorCode;
import com.xz.danhuaapi.exception.BusinessException;
import com.xz.danhuaapi.exception.ThrowUtils;
import com.xz.danhuaapi.mapper.UserInterfaceInfoMapper;
import com.xz.danhuaapi.model.dto.userinterfaceinfo.UserInterfaceInfoAddRequest;
import com.xz.danhuaapi.model.dto.userinterfaceinfo.UserInterfaceInfoQueryRequest;
import com.xz.danhuaapi.service.UserInterfaceInfoService;
import com.xz.danhuaapi.service.UserService;
import com.xz.danhuaapicommon.model.entity.User;
import com.xz.danhuaapicommon.model.entity.UserInterfaceInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

import static com.xz.danhuaapi.constant.CommonConstant.SORT_ORDER_ASC;
import static com.xz.danhuaapi.constant.CommonConstant.SORT_ORDER_DESC;

/**
* @author xuzhou
* @description 针对表【user_interface_info(用户调用接口关系)】的数据库操作Service实现
* @createDate 2024-07-04 14:46:33
*/
@Service
public class UserInterfaceInfoServiceImpl extends ServiceImpl<UserInterfaceInfoMapper, UserInterfaceInfo>
    implements UserInterfaceInfoService{

    @Resource
    private UserService userService;

    @Override
    public void validUserInterfaceInfo(UserInterfaceInfo userInterfaceInfo, boolean add) {
        ThrowUtils.throwIfNull(userInterfaceInfo);
        Long interfaceInfoId = userInterfaceInfo.getInterfaceInfoId();
        Long userId = userInterfaceInfo.getUserId();
        Integer leftNum = userInterfaceInfo.getLeftNum();
        Integer totalNum = userInterfaceInfo.getTotalNum();

        // 创建时，参数不能为空 / 是添加操作
        if (add) {
            // 检查所有数值变量是否为 null 或 0（如果 0 也被认为是无效）
            if (interfaceInfoId == null || interfaceInfoId == 0 ||
                    userId == null || userId == 0 ||
                    leftNum == null || leftNum <= 0 ||
                    totalNum == null || totalNum <= 0) {
                // 处理无效参数的情况
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数无效");
            }
        }

        if (userInterfaceInfo.getLeftNum() < 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "剩余次数不能小于0");
        }
    }

    @Override
    public long addUserInterfaceInfo(UserInterfaceInfoAddRequest userInterfaceInfoAddRequest, HttpServletRequest request) {

        UserInterfaceInfo userInterfaceInfo = new UserInterfaceInfo();
        BeanUtils.copyProperties(userInterfaceInfoAddRequest, userInterfaceInfo);

        this.validUserInterfaceInfo(userInterfaceInfo, true);
        User loginUser = userService.getLoginUser(request);
        userInterfaceInfo.setUserId(loginUser.getId());

        boolean result = this.save(userInterfaceInfo);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

        long newUserInterfaceInfoId = userInterfaceInfo.getId();

        return newUserInterfaceInfoId;
    }

    @Override
    public QueryWrapper<UserInterfaceInfo> getQueryWrapper(UserInterfaceInfoQueryRequest userInterfaceInfoQueryRequest) {
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        ThrowUtils.throwIfNull(userInterfaceInfoQueryRequest);

        Integer totalNum = userInterfaceInfoQueryRequest.getTotalNum();
        queryWrapper.eq(totalNum != null, "total_num", totalNum);

        Integer leftNum = userInterfaceInfoQueryRequest.getLeftNum();
        queryWrapper.eq(leftNum != null, "left_num", leftNum);

        Long interfaceInfoId = userInterfaceInfoQueryRequest.getInterfaceInfoId();
        queryWrapper.eq(interfaceInfoId != null, "interface_info_id", interfaceInfoId);

        Long userId = userInterfaceInfoQueryRequest.getUserId();
        queryWrapper.eq(userId != null, "user_id", userId);

        Integer status = userInterfaceInfoQueryRequest.getStatus();
        queryWrapper.eq(status != null, "status", status);

        String sortField = userInterfaceInfoQueryRequest.getSortField();
        String sortOrder = userInterfaceInfoQueryRequest.getSortOrder();
        if (SORT_ORDER_ASC.equals(sortOrder)) {
            // 升序
            if (StringUtils.isNotBlank(sortField)) {
                queryWrapper.orderByAsc(sortField);
            } else {
                queryWrapper.orderByAsc("create_time");
            }
        }
        if (SORT_ORDER_DESC.equals(sortOrder)) {
            // 降序
            if (StringUtils.isNotBlank(sortField)) {
                queryWrapper.orderByDesc(sortField);
            } else {
                queryWrapper.orderByDesc("create_time");
            }
        }

        return queryWrapper;
    }


    @Override
    public IPage<UserInterfaceInfo> getUserInterfaceInfoPage(Page<UserInterfaceInfo> userInterfaceInfoPage, HttpServletRequest request) {
        // 取出数据
        List<UserInterfaceInfo> interfaceinfoList = userInterfaceInfoPage.getRecords();
        if (CollectionUtils.isEmpty(interfaceinfoList)) {
            return new Page<>();
        }
        // 拷贝
        Page<UserInterfaceInfo> userInterfaceInfo = new Page<>();
        BeanUtils.copyProperties(userInterfaceInfoPage, userInterfaceInfo);

        // todo 关联查询用户信息 接口信息

        return userInterfaceInfoPage;
    }

    @Override
    public boolean invokeCount(long interfaceInfoId, long userId) {
        // 判断(其实这里还应该校验存不存在，这里就不用校验了，因为它不存在，也更新不到那条记录)
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 使用 UpdateWrapper 对象来构建更新条件
        UpdateWrapper<UserInterfaceInfo> updateWrapper = new UpdateWrapper<>();
        // 在 updateWrapper 中设置了两个条件：interfaceInfoId 等于给定的 interfaceInfoId 和 userId 等于给定的 userId。
        updateWrapper.eq("interface_info_id", interfaceInfoId);
        updateWrapper.eq("user_id", userId);
        // setSql 方法用于设置要更新的 SQL 语句。这里通过 SQL 表达式实现了两个字段的更新操作：
        // leftNum=leftNum-1和totalNum=totalNum+1。意思是将leftNum字段减一，totalNum字段加一。
        updateWrapper.setSql("left_num = left_num - 1, total_num = total_num + 1");
        // 最后，调用update方法执行更新操作，并返回更新是否成功的结果
        return this.update(updateWrapper);
    }

    @Override
    public UserInterfaceInfo getInvokeUserInterfaceInfo(long interfaceInfoId, long userId) {
        if (interfaceInfoId <= 0 || userId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<UserInterfaceInfo> queryWrapper = new QueryWrapper<>();
        // 在 updateWrapper 中设置了两个条件：interfaceInfoId 等于给定的 interfaceInfoId 和 userId 等于给定的 userId。
        queryWrapper.eq("interface_info_id", interfaceInfoId);
        queryWrapper.eq("user_id", userId);
        return this.getOne(queryWrapper);
    }
}




